package cn.rokhdelar.umbrsapi.management.service;

import cn.rokhdelar.umbrsapi.management.entity.SysUser;
import cn.rokhdelar.umbrsapi.management.repository.SysUserRepo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

@Service
public class SysUserService implements UserDetailsService {
    private final SysUserRepo sysUserRepo;
    private final PasswordEncoder passwordEncoder;

    public SysUserService(SysUserRepo sysUserRepo, PasswordEncoder passwordEncoder) {
        this.sysUserRepo = sysUserRepo;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return sysUserRepo.findByUsername(username);
    }

    public Page<SysUser> list(String name, Pageable pageable) {
        return sysUserRepo.findAllByNameContaining(name, pageable);
    }

    public Page<SysUser> listAllByUsername(String name, Pageable pageable) {
        return sysUserRepo.findAllByUsernameContaining(name, pageable);
    }

    public SysUser get(Long id) {
        return getUser(id);
    }

    public SysUser create(SysUser sysUser) {
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        return sysUserRepo.save(sysUser);
    }

    public SysUser update(Long id, SysUser sysUser) {
        SysUser user = sysUserRepo.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("指定ID的用户不存在，请确认。"));
        if (sysUser.getPassword() != null && StringUtils.isNotEmpty(sysUser.getPassword())) {
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        } else {
            sysUser.setPassword(user.getPassword());
        }
        return sysUserRepo.save(sysUser);
    }

    /**
     * 用于管理员设置密码，不验证原密码。
     * @param id
     * @param newPassword
     * @param repeatNewPassword
     * @return
     */
    public Boolean setPassword(Long id, String newPassword, String repeatNewPassword) {
        if(!passwordIsValid(newPassword) || !passwordIsValid(repeatNewPassword)) {
            throw new IllegalArgumentException("密码强度不够，请修改密码强度。");
        }

        if(!StringUtils.equals(newPassword, repeatNewPassword)) {
            throw new IllegalArgumentException("两次输入的新密码不一致，请重新输入。");
        }

        SysUser user = get(id);
        if (user == null) {
            throw new IllegalArgumentException("指定的用户不存在，请确认。");
        }

        user.setPassword(passwordEncoder.encode(newPassword));
        sysUserRepo.save(user);
        return Boolean.TRUE;
    }

    /**
     * 用于用户自主修改密码，需要验证原密码
     *
     * @param id
     * @param oldPassword
     * @param newPassword
     * @param repeatNewPassword
     * @return
     */
    public ResponseEntity<String> changePassword(Long id, String oldPassword, String newPassword, String repeatNewPassword) {
        if(!passwordIsValid(newPassword) || !passwordIsValid(repeatNewPassword)) {
            throw new IllegalArgumentException("密码强度不够，请修改密码强度。");
        }

        if(!StringUtils.equals(newPassword, repeatNewPassword)) {
            throw new IllegalArgumentException("两次输入的新密码不一致，请重新输入。");
        }

        SysUser user = get(id);
        if (user == null) {
            throw new IllegalArgumentException("指定的用户不存在，请确认。");
        }

        boolean matches = passwordEncoder.matches(oldPassword, user.getPassword());
        if(matches) {
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setPasswordExpired(Boolean.FALSE);
            sysUserRepo.save(user);
            return ResponseEntity.ok("密码修改成功，请重新登录。");
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("原密码错误，请检查。");
        }
    }

    public void delete(Long id) {
        sysUserRepo.deleteById(id);
    }

    private Boolean passwordIsValid(String password) {
        String pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{10,}$";
        return Pattern.matches(pattern, password);
    }

    private SysUser getUser(Long id) {
        return sysUserRepo.findById(id).orElse(null);
    }
}
